<?php

/**
 *  +----------------------------------------------------------------------
 *  | 草帽支付系统 [ WE CAN DO IT JUST THINK ]
 *  +----------------------------------------------------------------------
 *  | Copyright (c) 2018 http://www.iredcap.cn All rights reserved.
 *  +----------------------------------------------------------------------
 *  | Licensed ( https://www.apache.org/licenses/LICENSE-2.0 )
 *  +----------------------------------------------------------------------
 *  | Author: Brian Waring <BrianWaring98@gmail.com>
 *  +----------------------------------------------------------------------
 */

namespace app\auth\controller;

use app\common\library\exception\MissException;
use think\Session;
use org\login\Wxofficial;

/**
 * 所有的操作，都需要对输入执行参数校验，避免接口受到攻击。
 */
class Wechat extends BaseAuth
{


    /**
     * 统一授权
     *
     * @author zaite
     *
     */
    public function openid(){

        $callback_url = $this->request->request("callback") ?$this->request->request("callback") :$this->request->domain();

        Session::set('auth_callback_url',$callback_url);

        $wx = new Wxofficial();

        $login_url = url('auth/wechat/officialLogin','','',true);

        $accconfig = $this->logicAuth->getAllowedAccount('wx_auth');

        $this->redirect($wx->geturl($accconfig,$login_url));


    }

    /**
     * 微信公众号登陆，根据code，返回openid
     */
    public function officialLogin()
    {
        if(!input('?param.code')){
            return error_code(10068);
        }
        $scope = input('param.scope',1);        //公众号登陆类型，1是snsapi_userinfo，2是snsapi_base

        $wx = new Wxofficial();
        $accconfig = Session::get('auth_wx_config');
        $data= $wx->codeToInfo($accconfig,input('param.code'),input('param.state'),$scope);

        $callback_url = Session::get('auth_callback_url');
        $callback_url=$callback_url.'?'.http_build_query(['openid'=>$data['openid'],'auth_accountid'=>$accconfig['id']]);

        header('HTTP/1.1 301 Moved Permanently');
        header("Location: $callback_url");
        exit();
    }



}